# @author:Wei Junjie
# @time:2024/5/23 10:00
# @file blibli.py
# --*--coding: utf-8 --*--
"""
模块说明
"""
import random
import time,os
import requests
from fake_useragent import UserAgent
import re
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from urllib import parse

VIDEO_URL =LOG_PATH_SAVE = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'sourceStore', 'VIDEO', 'BLIBLI')

def quchong(ls):
    if not ls:
        return []
    first = ls[0]
    remain = ls[1:]
    # 不取
    if first in remain:
        return quchong(remain)
    # 取
    return [first] + quchong(remain)

# 搜索关键词返回搜索的结果页面
def search_keywords(keyword,page):
    new_keyword = parse.quote(keyword)
    url1='https://search.bilibili.com/all?keyword={}page={}'.format(new_keyword,page)
    header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0'}
    res=requests.get(url1,headers=header,timeout=20)
    return res

# 获取视频信息列表
def get_video_info(content):
    pattern1 = '(www.bilibili.com/video/\w+).*?alt="(.*?)"'
    data_list=re.findall(pattern1,content.text)

    print(data_list)

    quchong(data_list)
    return data_list

# 页面二 利用移动端显示正确的视频存储地址找到视频的真实地址
def second_page(name,url,title):
    header={"User-Agent":'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) EdgiOS/119.0.2151.105 Version/17.0 Mobile/15E148 Safari/604.1'}
    res=requests.get(url,headers=header)
    pattern1='readyVideoUrl":"(.*?)"'
    url_data=re.search(pattern1,res.text).group(1)
    video_data=requests.get(url_data,headers={'User-Agent':'Mozilla/5.0'}).content
    print(name,url_data)

    if os.path.exists(os.path.join(VIDEO_URL,title)):
        pass
    else:
        os.mkdir(os.path.join(VIDEO_URL,title))
    with open(os.path.join(VIDEO_URL, title, name + '.mp4'), 'wb') as f:
        f.write(video_data)

def main(keywords,page=1):
    search_result=search_keywords(keywords,page)
    data_list=get_video_info(search_result)
    quchong(data_list)
    for data in data_list:
        reg = re.compile(r'[/\\|*?<>]')
        name=''.join(reg.split(data[1]))
        video_url='https://'+data[0]

        second_page(name,video_url,keywords)

        time.sleep(random.randint(3,5))





if __name__ == '__main__':
    print(VIDEO_URL)


